const { tankGameState, connectedClients } = require('../../memoryStorage')
const { ShootPlayer } = require('./gameObjects')
const _ = require('lodash')
const debug = require('debug')('fps:tankStateSync')

const socketName = 'tank_game_state'

tankGameState.playerState = {}

const sync = (socket, io, client) => {
  const syncState = () => {
    io.emit(`${socketName}:sync_state`, {
      type: 'server_state',
      state: tankGameState
    })
  }

  const judgeHit = (bullet, entity) => {
    switch (entity.direction) {
      case 0:
      case 1:
        if (bullet.x >= entity.x && bullet.x <= entity.x + 20 && bullet.y >= entity.y - 1 && bullet.y <= entity.y + 22) {
          return true
        }
        break
      case 2:
      case 3:
        if (bullet.x >= entity.x - 1 && bullet.x <= entity.x + 22 && bullet.y >= entity.y && bullet.y <= entity.y + 20) {
          return true
        }
        break
      default:
        break
    }
  }

  const blink = (entity) => {
    const temp = entity.color
    entity.color = entity.color2
    entity.color2 = temp
  }

  socket.on(`${socketName}:join_game`, (params) => {
    debug(params)
    tankGameState.playerState[params.uuid] = new ShootPlayer(params)
    syncState()
  })

  socket.on(`${socketName}:playerAction`, params => {
    if (!tankGameState.playerState[params.uuid] || !tankGameState.playerState[params.uuid].alive) return
    tankGameState.playerState[params.uuid][params.action]()
    debug(params)
    syncState()
  })
  setInterval(() => {
    _.forEach(tankGameState.playerState, (item, key) => {
      item.bullets = item.bullets.filter(i => {
        return i.alive
      })
      item.bullets.forEach(bullet => {
        _.forEach(tankGameState.playerState, (entity) => {
          if (entity.uuid === item.uuid || !entity.alive || entity.hp < 0) return true
          if (judgeHit(bullet, entity)) {
            blink(entity)
            setTimeout(() => {
              blink(entity)
            }, 100)
            bullet.alive = false
            entity.hp -= 30
            if (entity.hp < 0) {
              setTimeout(() => {
                entity.alive = false
              }, 1000)
            }
          }
        })
        bullet.run()
      })
    })
    
    syncState()
  }, 16.6)
  
  socket.on('disconnect', () => {
    debug('disconnect', client.id)
    delete tankGameState.playerState[client.id]
    syncState()
    // socket.broadcast.emit('player_leave', client)
  })
}

module.exports = sync
